package io.youngking.modules.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.youngking.common.exception.RRException;
import io.youngking.common.utils.DateUtils;
import io.youngking.common.utils.ImageHelper;
import io.youngking.common.utils.R;
import io.youngking.common.utils.WeChatApplet;
import io.youngking.modules.comment.entity.CommentEntity;
import io.youngking.modules.comment.service.CommentService;
import io.youngking.modules.homepicture.entity.HomepictureEntity;
import io.youngking.modules.homepicture.service.HomepictureService;
import io.youngking.modules.hotelinfo.entity.HotelinfoEntity;
import io.youngking.modules.hotelinfo.service.HotelinfoService;
import io.youngking.modules.refundreceipt.entity.RefundreceiptEntity;
import io.youngking.modules.refundreceipt.service.RefundreceiptService;
import io.youngking.modules.roomnotice.entity.RoomnoticeEntity;
import io.youngking.modules.roomnotice.service.RoomnoticeService;
import io.youngking.modules.roomreceipt.entity.RoomreceiptEntity;
import io.youngking.modules.roomreceipt.service.RoomreceiptService;
import io.youngking.modules.roomtype.entity.RoomtypeEntity;
import io.youngking.modules.roomtype.service.RoomtypeService;
import io.youngking.modules.servertel.entity.ServertelEntity;
import io.youngking.modules.servertel.service.ServertelService;
import io.youngking.modules.surrounding.entity.SurroundingEntity;
import io.youngking.modules.surrounding.service.SurroundingService;
import io.youngking.modules.typeprice.entity.TypepriceEntity;
import io.youngking.modules.typeprice.service.TypepriceService;
import io.youngking.modules.wxappletsuserinfo.entity.WxappletsuserinfoEntity;
import io.youngking.modules.wxappletsuserinfo.service.WxappletsuserinfoService;
import io.youngking.modules.wxuserinfo.entity.WxuserinfoEntity;
import io.youngking.modules.wxuserinfo.service.WxuserinfoService;
import io.youngking.weixin4j.Weixin;
import io.youngking.weixin4j.WeixinException;
import io.youngking.weixin4j.model.message.template.TemplateData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.spec.InvalidParameterSpecException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.github.binarywang.wxpay.bean.request.BaseWxPayRequest.yuanToFen;
import static io.youngking.common.utils.Common.getRandomChar;
import static io.youngking.weixin4j.util.SignUtil.getSign;


/**
 * 小程序数据接口
 *
 * @author lifei
 */
@RestController
@RequestMapping("/app/weixin")
@PropertySource("classpath:weixin4j.properties")
public class WeixinController {
    @Autowired
    private HotelinfoService hotelinfoService;
    @Autowired
    private ServertelService servertelService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private RoomtypeService roomtypeService;
    @Autowired
    private RoomreceiptService roomreceiptService;
    @Autowired
    private HomepictureService homepictureService;
    @Autowired
    private SurroundingService surroundingService;
    @Autowired
    private WxuserinfoService wxuserinfoService;
    @Autowired
    private WxappletsuserinfoService wxappletsuserinfoService;
    @Autowired
    private RefundreceiptService refundreceiptService;
    @Autowired
    private TypepriceService typepriceService;
    @Autowired
    private RoomnoticeService roomnoticeService;
    @Autowired
    private WxPayService wxService;

    @Value("${weixin4j.oauth.appid}")
    private String appId;  //公众号appid
    @Value("${weixin4j.pay.partner.id}")
    private String payId;  //商户支付id
    @Value("${weixin4j.pay.partner.key}")
    private String paySerect;  //商户支付秘钥

    /**
     * 获取用户信息
     */
    @RequestMapping("/login")
    public R login(HttpServletRequest request) throws BadPaddingException, InvalidKeyException, UnsupportedEncodingException, IllegalBlockSizeException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidParameterSpecException {
        String code = request.getParameter("code");
        String encryptedData = request.getParameter("encryptedData");
        String iv = request.getParameter("iv");
        String sessionkey = WeChatApplet.getSessionKey(code);
        JSONObject userInfo = WeChatApplet.getUserInfo(encryptedData, sessionkey, iv);

        String openid = userInfo.getString("openId");
        String nickname = userInfo.getString("nickName");
        String sex = userInfo.getString("gender");
        String city = userInfo.getString("city");
        String province = userInfo.getString("province");
        String country = userInfo.getString("country");
        String language = userInfo.getString("language");
        String avatarurl = userInfo.getString("avatarUrl");
        WxappletsuserinfoEntity wxappletsuserinfoEntity = wxappletsuserinfoService.selectOne(new EntityWrapper<WxappletsuserinfoEntity>().eq("openid", openid));
        if (wxappletsuserinfoEntity == null) {
            WxappletsuserinfoEntity wxappletsuserinfoEntity1 = new WxappletsuserinfoEntity();
            wxappletsuserinfoEntity1.setOpenid(openid);
            wxappletsuserinfoEntity1.setNickname(nickname);
            wxappletsuserinfoEntity1.setSex(Integer.parseInt(sex));
            wxappletsuserinfoEntity1.setCity(city);
            wxappletsuserinfoEntity1.setProvince(province);
            wxappletsuserinfoEntity1.setCountry(country);
            wxappletsuserinfoEntity1.setLanguage(language);
            wxappletsuserinfoEntity1.setAvatarurl(avatarurl);
            wxappletsuserinfoEntity1.setAuthtime(new Date());
            wxappletsuserinfoService.insert(wxappletsuserinfoEntity1);
            return R.ok().put("userid", wxappletsuserinfoEntity1.getId()).put("openid", openid).put("session_key", sessionkey);
        } else {
            wxappletsuserinfoEntity.setOpenid(openid);
            wxappletsuserinfoEntity.setNickname(nickname);
            wxappletsuserinfoEntity.setSex(Integer.parseInt(sex));
            wxappletsuserinfoEntity.setCity(city);
            wxappletsuserinfoEntity.setProvince(province);
            wxappletsuserinfoEntity.setCountry(country);
            wxappletsuserinfoEntity.setLanguage(language);
            wxappletsuserinfoEntity.setAvatarurl(avatarurl);
            wxappletsuserinfoEntity.setAuthtime(new Date());
            wxappletsuserinfoService.updateById(wxappletsuserinfoEntity);
            return R.ok().put("userid", wxappletsuserinfoEntity.getId()).put("openid", openid).put("session_key", sessionkey);
        }
    }

    /**
     * 开始页轮播图信息
     */
    @RequestMapping("/homepicture")
    public R start(HttpServletRequest request) {
        List<HomepictureEntity> homepictureEntities = homepictureService.selectList(new EntityWrapper<HomepictureEntity>().eq("isshow", 0));
        String newlist = "";
        for (int i = 0; i < homepictureEntities.size(); i++) {
            String img = homepictureEntities.get(i).getUrl();

            if (StringUtils.isNotEmpty(img)) {
                String[] imglist = img.split(",");
                for (int j = 0; j < imglist.length; j++) {
                    String fileSavePath = "https://www.yanzuohotel.com/shenglian-fast/static/homepic/" + imglist[j];
                    newlist += fileSavePath + ",";
                }
            }
            if (StringUtils.isNotEmpty(newlist)) {
                newlist = newlist.substring(0, newlist.length() - 1);
            }
        }
        String[] newimglist = newlist.split(",");
        return R.ok().put("homepicture", newimglist);
    }

    /**
     * 首页信息（酒店信息、客服电话）
     */
    @RequestMapping("/hotelinfo")
    public R list() {
        EntityWrapper ew = new EntityWrapper();
        ew.setEntity(new HotelinfoEntity());
        ew.where("isdefault=0");
        HotelinfoEntity hotelinfo = hotelinfoService.selectOne(ew);
        String img = hotelinfo.getImgurl();
        String newlist = "";
        if (StringUtils.isNotEmpty(img)) {
            String[] imglist = img.split(",");
            for (int j = 0; j < imglist.length; j++) {
                String fileSavePath = "https://www.yanzuohotel.com/shenglian-fast/static/hotelinfo/" + imglist[j];
                newlist += fileSavePath + ",";
            }
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(newlist)) {
            newlist = newlist.substring(0, newlist.length() - 1);
        }
        hotelinfo.setImgurl(newlist);
        EntityWrapper entityWrapper = new EntityWrapper();
        entityWrapper.setEntity(new ServertelEntity());
        entityWrapper.where("isdefault=0");
        ServertelEntity servertelEntity = servertelService.selectOne(entityWrapper);
        return R.ok().put("hotelinfo", hotelinfo).put("servertel", servertelEntity);
    }


    /**
     * 评价列表
     */
    @RequestMapping("/evaluationlist")
    public R evaluationlist(HttpServletRequest request) {
        String page = request.getParameter("page");
        String pagesize = request.getParameter("count");
        Map<String, Object> map = new HashMap<>();
        map.put("offset", (Integer.parseInt(page) - 1) * Integer.parseInt(pagesize));
        map.put("limit", Integer.parseInt(pagesize));
        List<Map<String, Object>> commentEntities = commentService.getlist(map);
        for (int i = 0; i < commentEntities.size(); i++) {
            String img = commentEntities.get(i).get("imgurl").toString();
            String newlist = "";
            if (StringUtils.isNotEmpty(img)) {
                String[] imglist = img.split(",");
                for (int j = 0; j < imglist.length; j++) {
                    String fileSavePath = "https://www.yanzuohotel.com/shenglian-fast/static/comment/" + imglist[j];
                    newlist += fileSavePath + ",";
                }
            }
            if (org.apache.commons.lang.StringUtils.isNotEmpty(newlist)) {
                newlist = newlist.substring(0, newlist.length() - 1);
            }
            String[] newimglist = newlist.split(",");
            commentEntities.get(i).put("img", newimglist);
        }
        return R.ok().put("evaluationlist", commentEntities);
    }

    /**
     * 房型列表
     */
    @RequestMapping("/roomlist")
    public R roomlist() {
        List<RoomtypeEntity> roomtypeEntities = roomtypeService.selectList(new EntityWrapper<RoomtypeEntity>().eq("status", 0).orderBy("sort desc,id desc"));
        for (int i = 0; i < roomtypeEntities.size(); i++) {
            //处理房型图片
            String img = roomtypeEntities.get(i).getImgurl();
            String newlist = "";
            if (StringUtils.isNotEmpty(img)) {
                String[] imglist = img.split(",");
                for (int j = 0; j < imglist.length; j++) {
                    String fileSavePath = "https://www.yanzuohotel.com/shenglian-fast/static/roomtype/" + imglist[j];
                    newlist += fileSavePath + ",";
                }
            }
            if (org.apache.commons.lang.StringUtils.isNotEmpty(newlist)) {
                newlist = newlist.substring(0, newlist.length() - 1);
            }
            roomtypeEntities.get(i).setImgurl(newlist);

            //查看特殊价格
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            TypepriceEntity typepriceEntity = typepriceService.selectOne(
                    new EntityWrapper<TypepriceEntity>().eq("typeid", roomtypeEntities.get(i).getId())
                            .andNew("starttime<={0}", df.format(new Date()))
                            .andNew("endtime>={0}", df.format(new Date())));
            if (typepriceEntity != null) {
                roomtypeEntities.get(i).setPrice(typepriceEntity.getPrices());
            }
        }
        return R.ok().put("roomlist", roomtypeEntities);
    }

    /**
     * 周边信息
     */
    @RequestMapping("/surrounding")
    public R update() {
        //景区
        List<SurroundingEntity> servertelEntities = surroundingService.selectList(new EntityWrapper<SurroundingEntity>()
                .where("itype = 1").where("isshow = 0").orderBy("sort desc,id desc"));
        //交通
        List<SurroundingEntity> servertelEntities1 = surroundingService.selectList(new EntityWrapper<SurroundingEntity>()
                .where("itype = 2").where("isshow = 0").orderBy("sort desc,id desc"));
        //其他
        List<SurroundingEntity> servertelEntities2 = surroundingService.selectList(new EntityWrapper<SurroundingEntity>()
                .where("itype = 3").where("isshow = 0").orderBy("sort desc,id desc"));
        //酒店信息
        HotelinfoEntity hotelinfo = hotelinfoService.selectOne(new EntityWrapper<HotelinfoEntity>().eq("isdefault",0));
        return R.ok().put("spot", servertelEntities).put("transfer", servertelEntities1).put("other", servertelEntities2).put("hotelinfo",hotelinfo);
    }

    /**
     * 订单列表
     */
    @RequestMapping("/recepitlist")
    public R recepitlist(HttpServletRequest request) {
        String id = request.getParameter("userid");
        String type = request.getParameter("type");
        if (id == null) {
            return R.error();
        }
        EntityWrapper ew = new EntityWrapper();
        ew.setEntity(new RoomreceiptEntity());
        if (type.equals("0")) {
            ew.where("customerid={0}", id).in("status", "1,2").orderBy("id desc");
        } else {
            ew.where("customerid={0}", id).in("status", "3,4,5").orderBy("id desc");
        }
        List<RoomreceiptEntity> roomreceiptEntities = roomreceiptService.selectList(ew);
        return R.ok().put("recepitlist", roomreceiptEntities);
    }

    /**
     * 订单信息
     */
    @RequestMapping("/recepitinfo")
    public R recepitinfo(HttpServletRequest request) {
        String id = request.getParameter("receiptid");
        if (id == null) {
            return R.error();
        }
        RoomreceiptEntity roomreceiptEntity = roomreceiptService.selectById(id);
        RoomtypeEntity roomtypeEntity = roomtypeService.selectById(roomreceiptEntity.getRoomtype());
        roomreceiptEntity.setTypename(roomtypeEntity.getTypename());
        EntityWrapper ew = new EntityWrapper();
        ew.setEntity(new CommentEntity());
        ew.where("receiptid={0}", id);
        CommentEntity commentEntity = commentService.selectOne(ew);
        if (commentEntity != null) {
            String img = commentEntity.getImgurl();
            String newlist = "";
            if (StringUtils.isNotEmpty(img)) {
                String[] imglist = img.split(",");
                for (int j = 0; j < imglist.length; j++) {
                    String fileSavePath = "https://www.yanzuohotel.com/shenglian-fast/static/comment/" + imglist[j];
                    newlist += fileSavePath + ",";
                }
            }
            if (StringUtils.isNotEmpty(newlist)) {
                newlist = newlist.substring(0, newlist.length() - 1);
            }
            String[] newimglist = newlist.split(",");
            commentEntity.setImg(newimglist);
        }
        return R.ok().put("recepitinfo", roomreceiptEntity).put("ratings", commentEntity);
    }

    /**
     * 获取住宿时段单价
     */
    @RequestMapping("/getprice")
    public R getprice(HttpServletRequest request) throws ParseException {
        String typeid = request.getParameter("typeid");
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        if (typeid == null) {
            return R.error();
        }
        int num = DateUtils.daysBetween(starttime, endtime);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String, Object>> mapList = new LinkedList<>();
        for (int i = 0; i < num; i++) {
            Date nowtime = DateUtils.addDateDays(df.parse(starttime), i);
            TypepriceEntity typepriceEntity = typepriceService.selectOne(
                    new EntityWrapper<TypepriceEntity>().eq("typeid", typeid)
                            .andNew("starttime<={0}", nowtime)
                            .andNew("endtime>={0}", nowtime));
            Map<String, Object> map = new HashMap<>();
            if (typepriceEntity != null) {
                map.put("date", df.format(nowtime));
                map.put("price", typepriceEntity.getPrices());
            } else {
                RoomtypeEntity roomtypeEntity = roomtypeService.selectById(typeid);
                map.put("date", df.format(nowtime));
                map.put("price", roomtypeEntity.getPrice());
            }
            mapList.add(map);
        }
        return R.ok().put("dateprice", mapList);
    }


    private static boolean checkIP(String ip) {
        if (ip == null || ip.length() == 0 || "unkown".equalsIgnoreCase(ip)
                || ip.split(".").length != 4) {
            return false;
        }
        return true;
    }

    /**
     * 订单提交
     */
    @RequestMapping("/recepitadd")
    public R recepitadd(HttpServletRequest request) throws WxPayException, WeixinException {
        String typeid = request.getParameter("typeid");
        String num = request.getParameter("num");
        String holdtime = request.getParameter("holdtime");
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String remark = request.getParameter("remark");
        String starttime = request.getParameter("starttime");
        String endtime = request.getParameter("endtime");
        String money = request.getParameter("money");
        String customerid = request.getParameter("userid");
        String receiptcode = request.getParameter("receiptcode");

        if (customerid == null) {
            return R.error();
        }

        String ip = request.getHeader("x-forwarded-for");
        if (!checkIP(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (!checkIP(ip)) {
            ip = request.getRemoteAddr();
        }

        RoomreceiptEntity roomreceiptEntity = new RoomreceiptEntity();
        roomreceiptEntity.setRoomtype(Integer.parseInt(typeid));
        roomreceiptEntity.setRoomnum(Integer.parseInt(num));
        roomreceiptEntity.setHoldtime(holdtime);
        roomreceiptEntity.setUsername(username);
        roomreceiptEntity.setPhone(phone);
        roomreceiptEntity.setRemark(remark);
        roomreceiptEntity.setCustomerid(Integer.parseInt(customerid));
        roomreceiptEntity.setReceiptcode(receiptcode);
        roomreceiptEntity.setStatus(1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        try {
            roomreceiptEntity.setStarttime(df.parse(starttime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        try {
            roomreceiptEntity.setEndtime(df.parse(endtime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        roomreceiptEntity.setTotalshouldmoney(new BigDecimal(money));
        roomreceiptEntity.setTotalmoney(new BigDecimal(money));
        roomreceiptEntity.setChargetime(new Date());
        roomreceiptService.insert(roomreceiptEntity);

        //微信下单
/*        WxappletsuserinfoEntity wxappletsuserinfoEntity = wxappletsuserinfoService.selectById(customerid);
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setOpenid(wxappletsuserinfoEntity.getOpenid()); //用户openid
        orderRequest.setBody("晏坐民宿-订房支付"); //商品描述
        orderRequest.setOutTradeNo(receiptcode);  //订单号
        orderRequest.setTotalFee(yuanToFen(money));  //总金额
        orderRequest.setSpbillCreateIp(ip);  //终端IP
        orderRequest.setNotifyUrl("http://www.yanzuohotel.com/shenglian-fast/app/weixinapp/payurl"); //通知地址
        orderRequest.setTradeType("JSAPI"); //交易类型
        WxPayUnifiedOrderResult result = this.wxService.unifiedOrder(orderRequest);

        Map<String, String> map = new HashMap<>();
        map.put("appId", orderRequest.getAppid()); //小程序id
        map.put("timeStamp", String.valueOf((System.currentTimeMillis() / 1000)));  //当前时间戳
        map.put("nonceStr", getRandomChar(32));  //随机字符串(32位)
        map.put("package", "prepay_id=" + result.getPrepayId());  //统一下单接口返回的prepay_id
        map.put("signType", "MD5");  //签名方式
        String paySign = getSign(map, paySerect);
        map.put("paySign", paySign);  //签名
        return R.ok().put("receiptid", roomreceiptEntity.getId()).put("result", map);*/

        //房型库存减少
        RoomtypeEntity roomtypeEntity = roomtypeService.selectById(roomreceiptEntity.getRoomtype());
        roomtypeEntity.setStock(roomtypeEntity.getStock() - roomreceiptEntity.getRoomnum());
        roomtypeService.updateById(roomtypeEntity);

        //发送微信通知
        List<WxuserinfoEntity> wxuserinfoEntities = wxuserinfoService.selectList(
                new EntityWrapper<WxuserinfoEntity>().eq("isstaff", 1)
                        .eq("isdfnotice", 1).eq("subscribe", 1));
        Weixin weixin = new Weixin();
        for (int i = 0; i < wxuserinfoEntities.size(); i++) {
            if (StringUtils.isNotEmpty(wxuserinfoEntities.get(i).getOpenid())) {
                List<TemplateData> templateDataList = new ArrayList<>();
                TemplateData templateData = new TemplateData();
                templateData.setColor("red");
                templateData.setValue("您有一条新的订房信息，请及时查看!");
                templateData.setKey("first");
                templateDataList.add(templateData);
                TemplateData templateData1 = new TemplateData();
                templateData1.setColor("");
                templateData1.setValue(roomtypeEntity.getTypename());
                templateData1.setKey("keyword1");
                templateDataList.add(templateData1);
                TemplateData templateData2 = new TemplateData();
                templateData2.setColor("");
                templateData2.setValue(roomreceiptEntity.getUsername());
                templateData2.setKey("keyword2");
                templateDataList.add(templateData2);
                TemplateData templateData3 = new TemplateData();
                templateData3.setColor("");
                templateData3.setValue(df.format(roomreceiptEntity.getStarttime()));
                templateData3.setKey("keyword3");
                templateDataList.add(templateData3);
                TemplateData templateData4 = new TemplateData();
                templateData4.setColor("");
                templateData4.setValue(df.format(roomreceiptEntity.getEndtime()));
                templateData4.setKey("keyword4");
                templateDataList.add(templateData4);
                TemplateData templateData5 = new TemplateData();
                templateData5.setColor("");
                templateData5.setValue("微信");
                templateData5.setKey("keyword5");
                templateDataList.add(templateData5);
                TemplateData templateData6 = new TemplateData();
                templateData6.setColor("");
                templateData6.setValue("点击查看订单详情");
                templateData6.setKey("remark");
                templateDataList.add(templateData6);
                weixin.message().sendTemplateMessage(wxuserinfoEntities.get(i).getOpenid(), "j2RANzQd5NSFnh-pGm2Lkx0x8za0hU8mjGPWhZcwGT8", templateDataList, "http://www.yanzuohotel.com/fzfeedback?id=" + roomreceiptEntity.getId() + "&wxuserinfoid=" + wxuserinfoEntities.get(i).getId());

                //保存通知信息
                RoomnoticeEntity roomnoticeEntity = roomnoticeService.selectOne(
                        new EntityWrapper<RoomnoticeEntity>().eq("customerid", roomreceiptEntity.getCustomerid())
                                .andNew("receiptid", roomreceiptEntity.getId()));
                if (roomnoticeEntity == null) {
                    RoomnoticeEntity roomnoticeEntity1 = new RoomnoticeEntity();
                    roomnoticeEntity1.setCustomerid(roomreceiptEntity.getCustomerid());
                    roomnoticeEntity1.setReceiptid(roomreceiptEntity.getId());
                    roomnoticeEntity1.setSendtime(new Date());
                    roomnoticeService.insert(roomnoticeEntity1);
                }
            }
        }
        return R.ok().put("receiptid", roomreceiptEntity.getId());
    }

    /**
     * 支付失败（删除订单）
     */
    @RequestMapping("/payfail")
    public R payfail(HttpServletRequest request) {
        String receiptid = request.getParameter("receiptid");
        RoomreceiptEntity roomreceiptEntity = roomreceiptService.selectById(receiptid);
        if (roomreceiptEntity != null) {
            roomreceiptService.deleteById(receiptid);
        }
        return R.ok();
    }

    /**
     * 支付完成
     */
    @RequestMapping("/paysuccess")
    public R paysuccess(HttpServletRequest request) throws WeixinException {
        String receiptid = request.getParameter("receiptid");
        if (receiptid == null) {
            return R.error();
        }
        RoomreceiptEntity roomreceiptEntity = roomreceiptService.selectById(receiptid);
        //修改状态
        roomreceiptEntity.setStatus(1);
        roomreceiptEntity.setChargetime(new Date());
        roomreceiptService.updateById(roomreceiptEntity);

        //房型库存减少
        RoomtypeEntity roomtypeEntity = roomtypeService.selectById(roomreceiptEntity.getRoomtype());
        roomtypeEntity.setStock(roomtypeEntity.getStock() - roomreceiptEntity.getRoomnum());
        roomtypeService.updateById(roomtypeEntity);

        //发送微信通知
        List<WxuserinfoEntity> wxuserinfoEntities = wxuserinfoService.selectList(
                new EntityWrapper<WxuserinfoEntity>().eq("isstaff", 1)
                        .eq("isdfnotice", 1).eq("subscribe", 1));
        Weixin weixin = new Weixin();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < wxuserinfoEntities.size(); i++) {
            if (StringUtils.isNotEmpty(wxuserinfoEntities.get(i).getOpenid())) {
                List<TemplateData> templateDataList = new ArrayList<>();
                TemplateData templateData = new TemplateData();
                templateData.setColor("red");
                templateData.setValue("您有一条新的订房信息，请及时查看!");
                templateData.setKey("first");
                templateDataList.add(templateData);
                TemplateData templateData1 = new TemplateData();
                templateData1.setColor("");
                templateData1.setValue(roomtypeEntity.getTypename());
                templateData1.setKey("keyword1");
                templateDataList.add(templateData1);
                TemplateData templateData2 = new TemplateData();
                templateData2.setColor("");
                templateData2.setValue(roomreceiptEntity.getUsername());
                templateData2.setKey("keyword2");
                templateDataList.add(templateData2);
                TemplateData templateData3 = new TemplateData();
                templateData3.setColor("");
                templateData3.setValue(df.format(roomreceiptEntity.getStarttime()));
                templateData3.setKey("keyword3");
                templateDataList.add(templateData3);
                TemplateData templateData4 = new TemplateData();
                templateData4.setColor("");
                templateData4.setValue(df.format(roomreceiptEntity.getEndtime()));
                templateData4.setKey("keyword4");
                templateDataList.add(templateData4);
                TemplateData templateData5 = new TemplateData();
                templateData5.setColor("");
                templateData5.setValue("微信");
                templateData5.setKey("keyword5");
                templateDataList.add(templateData5);
                TemplateData templateData6 = new TemplateData();
                templateData6.setColor("");
                templateData6.setValue("点击查看订单详情");
                templateData6.setKey("remark");
                templateDataList.add(templateData6);
                weixin.message().sendTemplateMessage(wxuserinfoEntities.get(i).getOpenid(), "j2RANzQd5NSFnh-pGm2Lkx0x8za0hU8mjGPWhZcwGT8", templateDataList, "http://www.yanzuohotel.com/fzfeedback?id=" + roomreceiptEntity.getId() + "&wxuserinfoid=" + wxuserinfoEntities.get(i).getId());

                //保存通知信息
                RoomnoticeEntity roomnoticeEntity = roomnoticeService.selectOne(
                        new EntityWrapper<RoomnoticeEntity>().eq("customerid", roomreceiptEntity.getCustomerid())
                                .andNew("receiptid", roomreceiptEntity.getId()));
                if (roomnoticeEntity == null) {
                    RoomnoticeEntity roomnoticeEntity1 = new RoomnoticeEntity();
                    roomnoticeEntity1.setCustomerid(roomreceiptEntity.getCustomerid());
                    roomnoticeEntity1.setReceiptid(roomreceiptEntity.getId());
                    roomnoticeEntity1.setSendtime(new Date());
                    roomnoticeService.insert(roomnoticeEntity1);
                }
            }
        }
        return R.ok();
    }


    /**
     * 订单退款
     */
    @RequestMapping("/refundrecepit")
    public R refund(HttpServletRequest request) throws WxPayException {
        String refundcode = request.getParameter("refundcode");
        String recepitid = request.getParameter("receiptid");
        String imgurl = request.getParameter("imgurl");
        String reason = request.getParameter("reason");

        RoomreceiptEntity roomreceiptEntity = roomreceiptService.selectById(recepitid);

        if (roomreceiptEntity == null) {
            return R.error();
        }

        RefundreceiptEntity refundreceiptEntity = new RefundreceiptEntity();
        refundreceiptEntity.setRefundcode(refundcode);
        refundreceiptEntity.setReceiptid(Integer.parseInt(recepitid));
        refundreceiptEntity.setRefundreason(reason);
        refundreceiptEntity.setImgurl(imgurl);
        refundreceiptEntity.setRefundtime(new Date());
        refundreceiptService.insert(refundreceiptEntity);

        roomreceiptEntity.setStatus(5);
        roomreceiptService.updateById(roomreceiptEntity);

        //房型库存增加
        RoomtypeEntity roomtypeEntity = roomtypeService.selectById(roomreceiptEntity.getRoomtype());
        roomtypeEntity.setStock(roomtypeEntity.getStock() + roomreceiptEntity.getRoomnum());
        roomtypeService.updateById(roomtypeEntity);

        return R.ok();

        /*WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
        wxPayRefundRequest.setOutTradeNo(roomreceiptEntity.getReceiptcode());  //商户订单号
        wxPayRefundRequest.setOutRefundNo(refundcode);  //商户退款单号
        wxPayRefundRequest.setTotalFee(yuanToFen(roomreceiptEntity.getTotalmoney().toString())); //订单金额
        wxPayRefundRequest.setRefundFee(yuanToFen(roomreceiptEntity.getTotalmoney().toString())); //退款金额
        wxPayRefundRequest.setRefundDesc(reason);   //退款原因
        WxPayRefundResult refundResult = this.wxService.refund(wxPayRefundRequest);

        if (refundResult.getResultCode().equals("SUCCESS")) {
            RefundreceiptEntity refundreceiptEntity = new RefundreceiptEntity();
            refundreceiptEntity.setRefundcode(refundcode);
            refundreceiptEntity.setReceiptid(Integer.parseInt(recepitid));
            refundreceiptEntity.setRefundreason(reason);
            refundreceiptEntity.setImgurl(imgurl);
            refundreceiptEntity.setRefundtime(new Date());
            refundreceiptService.insert(refundreceiptEntity);

            roomreceiptEntity.setStatus(5);
            roomreceiptService.updateById(roomreceiptEntity);

            //房型库存增加
            RoomtypeEntity roomtypeEntity = roomtypeService.selectById(roomreceiptEntity.getRoomtype());
            roomtypeEntity.setStock(roomtypeEntity.getStock() - roomreceiptEntity.getRoomnum());
            roomtypeService.updateById(roomtypeEntity);
            return R.ok();
        } else {
            return R.error();
        }*/
    }

    /**
     * 退款图片上传
     */
    @PostMapping("/refundupload")
    public R refundupload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String fileSavePath = path + "/static/refund/";
        File f = new File(fileSavePath);
        // 判断路径是否存在，不存在则创建
        if (!f.exists()) {
            f.mkdirs();
        }
        ImageHelper.compress(file.getInputStream(), new File(fileSavePath + pictureName), 670);
        return R.ok().put("name", pictureName);
    }

    /**
     * 评论提交
     */
    @RequestMapping("/commentadd")
    public R commentadd(HttpServletRequest request) {
        String receiptid = request.getParameter("receiptid");
        String content = request.getParameter("content");
        String imgurl = request.getParameter("imgurl");
        if (receiptid == null) {
            return R.error();
        }
        CommentEntity commentEntity = new CommentEntity();
        RoomreceiptEntity roomreceiptEntity = roomreceiptService.selectById(receiptid);
        commentEntity.setReceiptid(Integer.parseInt(receiptid));
        commentEntity.setCustomerid(roomreceiptEntity.getCustomerid());
        WxappletsuserinfoEntity wxappletsuserinfoEntity = wxappletsuserinfoService.selectById(roomreceiptEntity.getCustomerid());
        commentEntity.setNickname(wxappletsuserinfoEntity.getNickname());
        commentEntity.setRoomtypeid(roomreceiptEntity.getRoomtype());
        RoomtypeEntity roomtypeEntity = roomtypeService.selectById(roomreceiptEntity.getRoomtype());
        commentEntity.setRoomtypename(roomtypeEntity.getTypename());
        commentEntity.setContents(content);
        commentEntity.setCommenttime(new Date());
        commentEntity.setImgurl(imgurl);
        commentService.insert(commentEntity);
        roomreceiptEntity.setStatus(4);
        roomreceiptService.updateById(roomreceiptEntity);
        return R.ok();
    }

    /**
     * 评论图片上传
     */
    @PostMapping("/commentupload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String fileSavePath = path + "/static/comment/";
        File f = new File(fileSavePath);
        // 判断路径是否存在，不存在则创建
        if (!f.exists()) {
            f.mkdirs();
        }
        ImageHelper.compress(file.getInputStream(), new File(fileSavePath + pictureName), 670);
        return R.ok().put("name", pictureName);
    }

    /**
     * 删除评论图片
     */
    @PostMapping("/picdelete")
    private R picdelete(HttpServletRequest request) {
        String name = request.getParameter("name");
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        String fileSavePath = path + "/static/comment/" + name;
        //删除文件夹中的图片文件
        File file = new File(fileSavePath);//文件路径
        file.delete();
        return R.ok();
    }


}
